    package com.kldy8.kldyw.logre;
    import android.animation.Animator;
    import android.animation.AnimatorListenerAdapter;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Handler;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AppCompatActivity;
    import android.telephony.TelephonyManager;
    import android.text.TextUtils;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.inputmethod.InputMethodManager;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.AutoCompleteTextView;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;


    import com.kldy8.kldyw.Constant;
    import com.kldy8.kldyw.Main2Activity;
    import com.kldy8.kldyw.R;
    import com.kldy8.kldyw.SystemSet;
    import com.kldy8.kldyw.WelComeActivity;
    import com.kldy8.kldyw.release.activity.ReleaseResumeActivity;
    import com.kldy8.kldyw.system.ServerApi;
    import com.kldy8.kldyw.system.ServerCallBack;
    import com.kldy8.kldyw.tools.TextUtil;

    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.Arrays;
    import java.util.List;

    import cn.smssdk.EventHandler;
    import cn.smssdk.SMSSDK;
    import cn.smssdk.utils.SMSLog;
    import okhttp3.Request;

    import static com.mob.tools.utils.R.getStringRes;

    /**
    *   注册
    * create at 2016/3/22 21:05
    */
    public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{

        // UI references.
        private AutoCompleteTextView mPhoneView;
        private EditText mPasswordView;
        private EditText mVerifyView;
        private View mProgressView;
        private View mRegisterView;
        private ActionBar actionBar ;
        private Button next_btn;
        private Button verification_btn;

        private String mphone;
        private String verification;
        private String password;
        private TextView user_accept_tv;
        Handler timeHandler = new Handler();
        private int count = 60;//倒计时
        private boolean check = true;
        private static InputMethodManager mInputMethodManager;
        private EventHandler handler;
        private EventHandler thehandler;

        private List<String> data_list_i;
        private List<String> data_list_ii;

        private ArrayAdapter<String> arr_adapter_i;
        private ArrayAdapter<String> arr_adapter_ii;

        Spinner spinner_i;
        Spinner spinner_ii;

        String[] companydata;
        String[] memberdata;
        String[] reg_type;

        private TimeCount time;

        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_regiter_first);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            init();
//            smsCallback();
        }
        /**
         * 注册
         *
         * @throws
         */
        private void register(String phone,String password ) throws Exception
        {

        }

        private void smsCallback()
        {
            handler = new EventHandler()
            {
                @Override
                public void afterEvent(int event, int result, Object data) {
                    if (result == SMSSDK.RESULT_COMPLETE)
                    {
                        Log.e("", "回调完成");
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                }
            };

            thehandler = new EventHandler() {
                public void afterEvent(int event, int result, Object data) {
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE)
                    {
                        /** 提交验证码 */
                        afterSubmit(result, data);
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE)
                    {
                        /** 获取验证码成功后的执行动作 */
                        Log.e("", " 获取验证码成功后的执行动作 ");
                        afterGet(result, data);
                    }
                }
            };
            SMSSDK.registerEventHandler(handler);
            SMSSDK.registerEventHandler(thehandler);// 注册短信回调
        }

        String strSpi;
        String strSpii;
        int intSpi;
        int intSpii;
        long idSpi;
        long idSpii;

        private void init()
        {
            companydata = getResources().getStringArray(R.array.company_type);
            memberdata = getResources().getStringArray(R.array.member_type);
            reg_type  = getResources().getStringArray(R.array.reg_type);
            data_list_i = Arrays.asList(reg_type);
            data_list_ii = Arrays.asList(memberdata);

             spinner_i = (Spinner) findViewById(R.id.spinner1);

             spinner_ii = (Spinner) findViewById(R.id.spinner2);

            arr_adapter_i= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list_i);
            //设置样式
            arr_adapter_i.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


            arr_adapter_ii= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list_ii);
            //设置样式
            arr_adapter_ii.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            //加载适配器
            spinner_i.setAdapter(arr_adapter_i);
            spinner_ii.setAdapter(arr_adapter_ii);

            spinner_i.setOnItemSelectedListener(
                    new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent,
                                                   View view, int position, long id)
                        {

                             if (position == 1)
                            {
                                data_list_ii = Arrays.asList(companydata);

                            }
                            else
                             {
                                 data_list_ii = Arrays.asList(memberdata);

                             }

                            strSpi = (String) spinner_i.getSelectedItem();
                            intSpi = position;
                            idSpi = id;

                            arr_adapter_ii= new ArrayAdapter<String>(RegisterActivity.this, android.R.layout.simple_spinner_item, data_list_ii);
                            //设置样式
                            arr_adapter_ii.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            spinner_ii.setAdapter(arr_adapter_ii);
                        }

                        public void onNothingSelected(AdapterView<?> parent)
                        {

                        }
                    });


            spinner_ii.setOnItemSelectedListener(
                    new AdapterView.OnItemSelectedListener() {
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
                        {
                            strSpii = (String) spinner_ii.getSelectedItem();
//                          intSpii = position;
                            intSpii =  SystemSet.getInstance().getAccountType().returnAccountTypeId(strSpii);
                            idSpii = id;
                        }

                        public void onNothingSelected(AdapterView<?> parent)
                        {

                        }
                    });




            SMSSDK.initSDK(this, Constant.APP_KEY,  Constant.APP_SECRET);
            actionBar = getSupportActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);
            mRegisterView=findViewById(R.id.login_form);
            mProgressView = findViewById(R.id.login_progress);
            mPhoneView= (AutoCompleteTextView) findViewById(R.id.phone_edt);
            mVerifyView= (EditText) findViewById(R.id.verification_edt);
            mPasswordView= (EditText) findViewById(R.id.password_edt);

            user_accept_tv= (TextView) findViewById(R.id.user_accept_tv);
            next_btn=(Button)findViewById(R.id.next_btn);
            verification_btn=(Button)findViewById(R.id.verification_btn);
            verification_btn.setOnClickListener(this);
            next_btn.setOnClickListener(this);
//            user_accept_tv.setOnClickListener(this);

            time = new TimeCount(verification_btn,60000, 1000);//构造CountDownTimer对象

        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            return super.onCreateOptionsMenu(menu);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item)
        {
            int id = item.getItemId();
            if (id == android.R.id.home)
            {
                this.finish();
            }
//        if (id == R.id.action_register)
//        {
//            return true;
//        }

            return super.onOptionsItemSelected(item);
        }
        public void onClick(View v){
            switch (v.getId()){
                case R.id.next_btn:
                    showProgress(true);
                    next_register();
                    break;
                case R.id.verification_btn:
                    if(check)
                    {
                        getCode();

                    }
                    break;
                case R.id.user_accept_tv:
                    Intent intent=new Intent();
//                    intent.setClass(RegisterActivity.this,UserAcceptActivity.class);
                    this.startActivity(intent);
                    break;
            }
        }

        private void next_register()
        {
            mPhoneView.setError(null);
            mVerifyView.setError(null);
            mPasswordView.setError(null);
            mphone=mPhoneView.getText().toString();
            verification=mVerifyView.getText().toString();
            password=mPasswordView.getText().toString();

            boolean cancel = false;
            View focusView = null;

            if (TextUtils.isEmpty(password) || !isPasswordValid(password)) {
                mPasswordView.setError(getString(R.string.error_invalid_password));
                focusView = mPasswordView;
                cancel = true;
                showProgress(false);

            }
            // Check for a valid email address.
            if (TextUtils.isEmpty(mphone)) {
                mPhoneView.setError(getString(R.string.error_field_required));
                focusView = mPhoneView;
                cancel = true;
                showProgress(false);

            }else if (TextUtil.isEmpty(verification)) {
                mVerifyView.setError(getString(R.string.error_ver_required));
                focusView = mVerifyView;
                cancel = true;
                showProgress(false);

            }else if (!TextUtil.isMobileNumber(mphone)) {
                mPhoneView.setError(getString(R.string.error_invalid_email));
                focusView = mPhoneView;
                cancel = true;
                showProgress(false);

            }
            if (cancel)
            {
                // There was an error; don't attempt login and focus the first
                // form field with an error.
                focusView.requestFocus();
                showProgress(false);
            }
            else
            {
//              SMSSDK.submitVerificationCode("86", mphone, verification);.
                TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
                String client_key = tm.getDeviceId();

                  ServerApi.registration(mphone, password, verification, "" +intSpi, ""+intSpii,client_key,
                          new ServerCallBack()
                          {

                              @Override
                              public void onError(Request request, Exception e)
                              {
                                  showProgress(false);
                                  Toast.makeText(RegisterActivity.this,"网络错误，请稍后重试",Toast.LENGTH_LONG).show();
                              }

                              @Override
                              public void onResponse(String response) throws JSONException
                              {
                                  showProgress(false);
                                  Log.e("......",response.toString());
                                  JSONObject jsonObject = new JSONObject(response);
                                  if ("0".equals(jsonObject.optString("code")))
                                  {
                                      JSONObject objectData = jsonObject.optJSONObject("data");
                                      String username =  objectData.optString("username");
                                      String token =  objectData.optString("token");
                                      String member_id =  objectData.optString("member_id");

                                      SystemSet.getInstance().setToken(token);
                                      SystemSet.getInstance().setF_person(""+intSpi);
                                      SystemSet.getInstance().setMember_id(member_id);

                                      Intent i=new Intent();
                                      i.setClass(RegisterActivity.this, Main2Activity.class);
                                      startActivity(i);
                                      overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);

                                  }
                                  else if ("10006".equals(jsonObject.optString("code")))
                                  {
                                      Toast.makeText(RegisterActivity.this,"验证码错误",Toast.LENGTH_LONG).show();
                                  }
                                  else if ("10007".equals(jsonObject.optString("code")))
                                  {
                                      Toast.makeText(RegisterActivity.this,"用户名已存在",Toast.LENGTH_LONG).show();
                                  }
                                  else if ("10008".equals(jsonObject.optString("code")))
                                  {
                                      Toast.makeText(RegisterActivity.this,"用户类型非法",Toast.LENGTH_LONG).show();
                                  }
                                  else if ("10009".equals(jsonObject.optString("code")))
                                  {
                                      Toast.makeText(RegisterActivity.this,"电话号码格式错误",Toast.LENGTH_LONG).show();
                                  }
                                  else if ("10010".equals(jsonObject.optString("code")))
                                  {
                                      Toast.makeText(RegisterActivity.this,"电话号码已有绑定的账号",Toast.LENGTH_LONG).show();
                                  }
                                  else if ("10011".equals(jsonObject.optString("code")))
                                  {
                                      Toast.makeText(RegisterActivity.this,"密码格式不合法",Toast.LENGTH_LONG).show();
                                  }
                                  else
                                  {
                                      Toast.makeText(RegisterActivity.this,"注册失败，请填入正确资料",Toast.LENGTH_LONG).show();
                                  }
                              }
                          });
            }

        }

        /**
         * 验证密码长度
         * @param password
         * @return
         */
        private boolean isPasswordValid(String password) {
            //TODO: Replace this with your own logic
            return password.length() > 4;
        }

       private void startNext() {
           Intent intent = new Intent(RegisterActivity.this,
                   LoginActivity.class);
           startActivity(intent);
           finish();
       }

       //获取验证码
        private void getCode()
        {
            mVerifyView.setError(null);
            mphone=mPhoneView.getText().toString();
                if(TextUtil.isEmpty(mphone)) {
                    mPhoneView.setError(getString(R.string.isphone_null_toast));
                    return;
                }
                if(!TextUtil.isMobileNumber(mphone)) {
                    mPhoneView.setError(getString(R.string.isphone_not_toast));
                    return;
                }
//            SMSSDK.getVerificationCode("86", mphone);
//            checkCompelte=false;
            time.start();//开始计时
            ServerApi.SMS(mphone,ServerApi.SMS_TYPE_REGISTER ,new ServerCallBack()
            {
                @Override
                public void onError(Request request, Exception e)
                {
                    Log.e("onError",e.getMessage());
                    Toast.makeText(RegisterActivity.this,"网络错误，请稍后重试",Toast.LENGTH_LONG).show();
                }

                @Override
                public void onResponse(String response) throws JSONException
                {
                    Log.e("response",response.toString());
                    JSONObject object = new JSONObject(response);
                    if ("0".equals(object.optString("code")))
                    {
                        Toast.makeText(RegisterActivity.this,"发送成功，请查看手机验证码",Toast.LENGTH_LONG).show();
                    }
                    else if ("10002".equals(object.optString("code")))
                    {
                        Toast.makeText(RegisterActivity.this,"此手机号码已注册",Toast.LENGTH_LONG).show();
                    }
                    else if ("10006".equals(object.optString("code")))
                    {
                        Toast.makeText(RegisterActivity.this,"验证码错误",Toast.LENGTH_LONG).show();
                    }
                    else if ("10007".equals(object.optString("code")))
                    {
                        Toast.makeText(RegisterActivity.this,"用户名已存在",Toast.LENGTH_LONG).show();
                    }
                    else if ("10008".equals(object.optString("code")))
                    {
                        Toast.makeText(RegisterActivity.this,"用户类型非法",Toast.LENGTH_LONG).show();
                    }
                    else if ("10009".equals(object.optString("code")))
                    {
                        Toast.makeText(RegisterActivity.this,"电话号码格式错误",Toast.LENGTH_LONG).show();
                    }
                    else if ("10010".equals(object.optString("code")))
                    {
                        Toast.makeText(RegisterActivity.this,"电话号码已有绑定的账号",Toast.LENGTH_LONG).show();
                    }
                    else if ("10011".equals(object.optString("code")))
                    {
                        Toast.makeText(RegisterActivity.this,"密码格式不合法",Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        Toast.makeText(RegisterActivity.this,"注册失败，请填入正确资料",Toast.LENGTH_LONG).show();
                    }
                }
            });
        }

        /**
         * 重新获取验证码倒计时
         * */
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                count--;
                if (count > 0)
                {
                    verification_btn.setText("重新获取(" + count + ")");
                    verification_btn.setClickable(false);
                    verification_btn.setTextSize(15);
                    timeHandler.postDelayed(this, 1000);
                }
                else if (count == 0)
                {
                    count = 60;
                    check = true;
                    verification_btn.setText("重新获取");
                    verification_btn.setClickable(true);
                    timeHandler.removeCallbacks(runnable, 1000);
                }
            }

        };

        /**
         * 获取验证码成功后执行的动作
         *
         * @param result
         * @param data
         */
        private void afterGet(final int result, final Object data) {
            runOnUiThread(new Runnable() {
                public void run() {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        check = false;
                        timeHandler.postDelayed(runnable, 1000);
                        Toast.makeText(RegisterActivity.this, "已将验证码发送到该手机！",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        ((Throwable) data).printStackTrace();
                        Throwable throwable = (Throwable) data;
                        // 根据服务器返回的网络错误，给toast提示
                        try {
                            JSONObject object = new JSONObject(
                                    throwable.getMessage());
                            String des = object.optString("detail");
                            if (!TextUtils.isEmpty(des)) {
                                Toast.makeText(RegisterActivity.this, des,
                                        Toast.LENGTH_SHORT).show();
                                return;
                            }
                        } catch (JSONException e) {
                            SMSLog.getInstance().w(e);
                        }
                        // / 如果木有找到资源，默认提示
                        int resId = getStringRes(RegisterActivity.this,
                                "smssdk_network_error");
                        if (resId > 0) {
                            Toast.makeText(RegisterActivity.this, resId,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
        }

        protected void onDestroy() {
            SMSSDK.unregisterAllEventHandler();
            super.onDestroy();

        }
        /**
         * TODO 跳转dialog
         */
        private void showProgress(final boolean show) {
            // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
            // for very easy animations. If available, use these APIs to fade-in
            // the progress spinner.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
                int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

                mRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
                mRegisterView.animate().setDuration(shortAnimTime).alpha(
                        show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
                    }
                });

                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                mProgressView.animate().setDuration(shortAnimTime).alpha(
                        show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                    }
                });
            } else {
                // The ViewPropertyAnimator APIs are not available, so simply show
                // and hide the relevant UI components.
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                mProgressView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        }
        /**
         * 验证码正确 进行页面跳转
         *
         * @param result
         * @param data
         */
        private void afterSubmit(final int result, final Object data) {
            runOnUiThread(new Runnable() {
                public void run() {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        Log.e("", "验证码正确");
                        count = 60;
                        check = true;
                        verification_btn.setText("重新获取");
                        timeHandler.removeCallbacks(runnable);
                        showProgress(true);
                        try {
                            register(mPhoneView.getText().toString(),
                                    mPasswordView.getText().toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        mVerifyView.setError(null);
                        ((Throwable) data).printStackTrace();
                        mVerifyView.setError("验证码错误");
                    }
                }
            });
        }
        // 隐藏软件盘
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                if (RegisterActivity.this.getCurrentFocus() != null
                        && RegisterActivity.this.getCurrentFocus().getWindowToken() != null) {
                    mInputMethodManager.hideSoftInputFromWindow(RegisterActivity.this
                                    .getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
            return super.onTouchEvent(event);
        }
    }
